package cn.cuilan.test.thread;

import java.util.concurrent.Semaphore;

/**
 * Semaphore 信号量方式实现
 *
 * @author zhangyan
 * @since 2023/3/10
 */
public class SemaphorePrint {

    private final static Semaphore s1 = new Semaphore(1);
    private final static Semaphore s2 = new Semaphore(0);
    private final static Semaphore s3 = new Semaphore(0);
    private final static Semaphore s4 = new Semaphore(0);

    public void print(String context, Semaphore current, Semaphore next) {
        for (int i = 0; i < 3; i++) {
            try {
                // 获得信号量，阻塞当前线程，即信号量的计数器减1为0
                current.acquire();
                System.out.println(Thread.currentThread().getName() + ": " + context);
                // 唤醒下一个线程，即信号量的计数器加1
                next.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        SemaphorePrint sp = new SemaphorePrint();
        new Thread(() -> sp.print("A", s1, s2), "Thread-a").start();
        new Thread(() -> sp.print("B", s2, s3), "Thread-b").start();
        new Thread(() -> sp.print("C", s3, s4), "Thread-c").start();
        new Thread(() -> sp.print("D", s4, s1), "Thread-d").start();
    }

}
